package com.qianfeng.smartdevices.security;


//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼            BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  


import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartdevices.dto.R;
import com.qianfeng.smartdevices.pojo.BaseUser;
import com.qianfeng.smartdevices.pojo.Menu;
import com.qianfeng.smartdevices.pojo.Role;
import com.qianfeng.smartdevices.service.MenusService;
import com.qianfeng.smartdevices.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by jackiechan on 2021/10/18 11:18
 *
 * @author jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {


    private RoleService roleService;


    private MenusService menusService;


    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setMenusService(MenusService menusService) {
        this.menusService = menusService;
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    /**
     * 认证成功,代表你的账号和密码是对的,登陆成功了
     *
     * @param request
     * @param response
     * @param authentication 我们返回的认证信息
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //在这里把你想在登录成功之后要做的事情做出来,必须把用户的权限查询出来保存起来
        System.err.println("登录成功了");

        BaseUser baseUser = (BaseUser) authentication.getPrincipal();//获取到当前的用户信息
        System.err.println(baseUser);
        System.err.println(authentication.getCredentials());
//        List<GrantedAuthority> grantedAuthorities = (List<GrantedAuthority>) authentication.getAuthorities();//会报错 java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection.add(Collections.java:1057) 当前获取到的集合是不可修改的
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();//用于保存用户所有的权限的集合

        Long uid = baseUser.getUid();//获取到当前登录的用户的 id
        //根据用户 id 查询用户的角色,然后查询菜单
        List<Role> roles = roleService.findRoleByUserId(uid);
        roles.forEach(role -> {//遍历角色,查询每个角色的菜单,并设置进去
            List<Menu> menuList = menusService.findMenuByRoleId(role.getId());
            role.setMenuList(menuList);
            //我们需要将查询到的角色和权限设置给当前登录的用户
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));//给用户添加角色
            //设置权限
            //将所有的权限设置到用户身上
            grantedAuthorities.addAll(menuList.stream().map(Menu::getPerms).map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        });
        baseUser.setRoleList(roles);//保存了用户的所有的角色,方便在其他地方使用
        //刷新权限,重新给用户授权
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(baseUser, authentication.getCredentials(), grantedAuthorities));
        //更新登录时间,发送一个事件,事件中需要携带数据 用户的 id
        if (request.getHeader("ismobile") != null) {
            R r = R.setOK();
            response.setContentType(MediaType.APPLICATION_JSON_UTF8.toString());
            response.getWriter().write(objectMapper.writeValueAsString(r));
            return;
        }

        response.sendRedirect("/index.html");
    }
}
